package com.lanou.service.impl;

import com.lanou.entity.Commodity;
import com.lanou.service.CartService;
import com.lanou.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by QuChao on 2018/12/3
 */
@Service
public class CartServiceImpl implements CartService {
    @Value("${CART_JSON_URL}")
    private String CART_JSON_URL;

    @Value("${CART_EDIT_JSON_URL}")
    private String CART_EDIT_JSON_URL;

    @Value("${CART_DEL_URL}")
    private String CART_DEL_URL;

    @Value("${CART_EDIT_STATUS_URL}")
    private String CART_EDIT_STATUS_URL;

    @Value("${CART_EDIT_CHECKALL_URL}")
    private String CART_EDIT_CHECKALL_URL;

    @Override
    public List<Map<String, Object>> getCartListByUid(Map<String, Object> userMap) {
        List<Commodity> commodities = HttpClientUtils.getList(CART_JSON_URL + "?userId=" + userMap.get("userId"), Commodity.class);
        List<Map<String, Object>> list = new ArrayList<>();
        for (Commodity commodity : commodities) {
            Map<String, Object> map = new HashMap<>();
            map.put("checked", commodity.getStatus());
            map.put("productId", commodity.getId());
            map.put("productImg", commodity.getImg().split(",")[0]);
            map.put("productName", commodity.getTitle());
            map.put("productNum", commodity.getAmount());
            map.put("salePrice", commodity.getPrice());
            list.add(map);
        }
        return list;
    }

    @Override
    @Transactional
    public Map<String, Object> editByUid(Map<String, Object> map) {
        if (map.get("checked") != null) {
            return HttpClientUtils.getObject(CART_EDIT_STATUS_URL + "?status=" + map.get("checked") + "&userId=" + map.get("userId") + "&itemId" + map.get("productId"), Map.class);
        } else {
            return HttpClientUtils.getObject(CART_EDIT_JSON_URL + "?userId=" + map.get("userId") + "&itemId=" + map.get("productId") + "&num=" + map.get("productNum"), Map.class);
        }
    }

    @Override
    public Map<String, Object> delete(Map<String, Object> map) {
        return HttpClientUtils.getObject(CART_DEL_URL + "?userId=" + map.get("userId") + "&itemId" + map.get("productId"), Map.class);
    }

    @Override
    public Map<String, Object> checkAll(Map<String, Object> map) {
        int status = 0;
        if ((boolean) map.get("checked")) {
            status = 1;
        }
        return HttpClientUtils.getObject(CART_EDIT_CHECKALL_URL + "?userId=" + map.get("userId") + "&status=" + status, Map.class);
    }
}
